package com.da.core.context;

import com.da.core.util.Seq;
import com.da.core.util.Utils;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Optional;

/**
 * @author da
 * @time 2023/9/16 上午 10:09
 */
public class Response implements OutFunc {
    private final Context context;

    public Response(Context context) {
        this.context = context;
    }

    public void TEXT(int code, String message) {
        context.setStatus(code);
        context.setStatusMsg("OK");
        context.setHeader("Content-Type", "text/plain;charset=utf-8;");
        context.setData(message.getBytes(StandardCharsets.UTF_8));
    }

    public void HTML(int code, String message) {
        context.setStatus(code);
        context.setStatusMsg("OK");
        context.setHeader("Content-Type", "text/html;charset=utf-8;");
        context.setData(message.getBytes(StandardCharsets.UTF_8));
    }

    public void HTML(int code, File html) {
        Seq<String> lines = Utils.readLines(Paths.get(html.getPath()));
        this.HTML(200, lines.reduce((a, b) -> a + b + "\n"));
    }

    public void JSON(int code, String message) {
        context.setStatus(code);
        context.setStatusMsg("OK");
        context.setHeader("Content-Type", "application/json;charset=utf-8;");
        context.setData(message.getBytes(StandardCharsets.UTF_8));
    }

    public void FILE(int code, File file) {
        try {
            context.setStatus(code);
            context.setStatusMsg("OK");
//            通过文件类型设置对应的Content-Type
            context.setHeader("Content-Type", Utils.getFileContentType(file));
            context.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
            context.setHeader("Content-Length", String.valueOf(file.length()));
            byte[] buffer = new byte[(int) file.length()];
            Path path = Paths.get(file.getPath());
            FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ);
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) fileChannel.size());
            fileChannel.read(byteBuffer);
            byteBuffer.flip();
            byteBuffer.get(buffer);
            context.setData(buffer);
        } catch (Exception e) {
            context.setException(e);
        }
    }

    //    拼接SSE传输的数据格式
    public void pushSSEData(String message) {
        String eventName = "update";
//        最后的 \n\n 表示这条消息结束
        String sseEventData = "data: {\"event\":\"" + eventName + "\",\"data\":\"" + message + "\"}\n\n";
        context.setData(sseEventData.getBytes(StandardCharsets.UTF_8));
//        刷新数据到浏览器
        context.flashDataToResponse();
    }
}
